package com.niiwoo.civet.mobile.lanmao.handler;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.niiwoo.civet.account.service.AccountDubboService;
import com.niiwoo.tripod.lanmao.enums.LanMaoGatewayServiceNameEnum;
import com.niiwoo.tripod.lanmao.enums.UserAuthorizationEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * Created by zhangwanli on 2017/11/29.
 */
@Component
@Slf4j
public class UserAuthorizationNotifyHandler implements LanMaoNotifyHandler {

    @Reference(version = "1.0.0")
    private AccountDubboService accountDubboService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean supports(String serviceName) {
        return LanMaoGatewayServiceNameEnum.USER_AUTHORIZATION.name().equals(serviceName);
    }

    @Override
    public HandleResult handle(JSONObject json) {
        log.info("用户授权回调,请求报文={}", JSON.toJSONString(json));
        String platformUserNo = json.getString("platformUserNo");
        log.info("用户授权回调,平台用户编号={},请求报文={}", platformUserNo, JSON.toJSONString(json));
        String requestNo = json.getString("requestNo");
        String redirectUrl=redisTemplate.opsForValue().get(requestNo);
        log.info("用户授权回调,平台用户编号={},跳转地址={}", platformUserNo, redirectUrl);
        String authList = json.getString("authList");
        Set<UserAuthorizationEnum> authorizations = Splitter.on(",").splitToList(authList).stream()
                .map(UserAuthorizationEnum::valueOf).collect(Collectors.toSet());
        accountDubboService.notifyEnabledUserAuthorization(platformUserNo, requestNo, authorizations);
        HandleResult result = new HandleResult();
        result.setNeedAck(true);
        result.setRequestNo(requestNo);
        Set<String> authNames = authorizations.stream().map(UserAuthorizationEnum::getDesc).collect(Collectors.toSet());
        result.setData("用户授权处理成功:" + Joiner.on(",").skipNulls().join(authNames));
        return result;
    }

}
